package com.bear.atlassianmcp.oauth.strategy;

import com.bear.atlassianmcp.common.util.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * Basic Authentication 策略实现
 * 支持传统的用户名密码认证方式
 */
@Component
public class BasicAuthStrategy implements AuthenticationStrategy {
    
    private static final Logger logger = LoggerFactory.getLogger(BasicAuthStrategy.class);
    
    private final RestTemplate oauthRestTemplate;
    
    public BasicAuthStrategy(RestTemplate oauthRestTemplate) {
        this.oauthRestTemplate = oauthRestTemplate;
    }
    
    @Override
    public HttpHeaders createAuthHeaders(ToolContext toolContext) {
        HttpHeaders headers = new HttpHeaders();
        
        // 设置Content-Type
        headers.set("Content-Type", "application/json");
        headers.set("Accept", "application/json");
        
        // 从请求头获取授权信息
        String auth = getAuthorizationFromContext(toolContext);
        if (auth == null) {
            throw new RuntimeException("No authorization found in request headers");
        }
        
        headers.set("Authorization", auth);
        logger.debug("Using Basic Auth from request headers");
        
        return headers;
    }
    
    @Override
    public void validateAuthConfiguration() {
        // Basic Auth 的配置验证在运行时通过请求头进行
        // 这里不需要预先验证配置文件
        logger.debug("Basic Auth configuration validation - runtime validation via request headers");
    }
    
    @Override
    public AuthenticationType getAuthenticationType() {
        return AuthenticationType.BASIC_AUTH;
    }
    
    @Override
    public boolean supportsServiceType(ServiceType serviceType) {
        // Basic Auth 支持所有服务类型
        return true;
    }
    
    @Override
    public String testConnection(ToolContext toolContext, String baseUrl) {
        logger.debug("Testing Basic Auth connection to: {}", baseUrl);
        
        try {
            // 构建测试URL - 获取当前用户信息
            String testUrl = baseUrl + "/rest/api/2/myself";
            
            HttpHeaders headers = createAuthHeaders(toolContext);
            HttpEntity<String> entity = new HttpEntity<>(headers);
            
            ResponseEntity<String> response = oauthRestTemplate.exchange(
                testUrl, HttpMethod.GET, entity, String.class);
            
            if (response.getStatusCode().is2xxSuccessful()) {
                return "Basic Auth connection successful!";
            } else {
                return "Basic Auth connection failed with status: " + response.getStatusCode();
            }
            
        } catch (Exception e) {
            logger.error("Basic Auth connection test failed: {}", e.getMessage());
            throw new RuntimeException("Basic Auth connection test failed: " + e.getMessage(), e);
        }
    }
    
    /**
     * 从ToolContext中获取授权信息
     *
     * @param toolContext 工具上下文
     * @return 授权信息，如果获取失败返回null
     */
    private String getAuthorizationFromContext(ToolContext toolContext) {
        if (toolContext == null) {
            logger.error("ToolContext is null, cannot retrieve authorization");
            return null;
        }
        
        try {
            String authorization = SessionUtil.getAuthorization(toolContext);
            if (authorization != null && authorization.startsWith("Basic ")) {
                logger.debug("Successfully retrieved Basic authorization from request headers");
                return authorization;
            } else if (authorization != null) {
                logger.error("Authorization header found but not in Basic format: {}",
                           authorization.substring(0, Math.min(authorization.length(), 10)) + "...");
                return null;
            } else {
                logger.error("No authorization header found in request");
                return null;
            }
        } catch (Exception e) {
            logger.error("Failed to get authorization from context: {}", e.getMessage());
            return null;
        }
    }
    
    /**
     * 检查授权头是否为Basic Auth格式
     */
    public boolean isBasicAuth(String authorizationHeader) {
        return authorizationHeader != null && authorizationHeader.startsWith("Basic ");
    }
    
    /**
     * 从Basic Auth头中提取用户名
     */
    public String extractUsername(String basicAuthHeader) {
        if (!isBasicAuth(basicAuthHeader)) {
            return null;
        }
        
        try {
            String base64Credentials = basicAuthHeader.substring("Basic ".length());
            byte[] decodedBytes = java.util.Base64.getDecoder().decode(base64Credentials);
            String credentials = new String(decodedBytes, java.nio.charset.StandardCharsets.UTF_8);
            
            int colonIndex = credentials.indexOf(':');
            if (colonIndex > 0) {
                return credentials.substring(0, colonIndex);
            }
        } catch (Exception e) {
            logger.error("Failed to extract username from Basic Auth header: {}", e.getMessage());
        }
        
        return null;
    }
}
